package com.simple.editor.ui;

import com.simple.editor.action.ActionManager;
import com.simple.editor.action.EditorUIAction;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;

/**
 * {@link MenuPane} provides application menu
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vlad
 * Date: 6/2/13
 * Time: 3:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class MenuPane extends JMenuBar {
    final JMenuItem saveAllFile;
    private final ActionManager actionManager;

    public MenuPane(final ActionManager actionManager) {
        this.actionManager = actionManager;
        setLayout(new FlowLayout(FlowLayout.LEFT));

        final JFileChooser dirChooser = new JFileChooser();
        dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        final JMenuItem openItem = createMenuItem("/open_btn.png");
        openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                final int returnVal = dirChooser.showOpenDialog(MenuPane.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    final File file = dirChooser.getSelectedFile();
                    MenuPane.this.actionManager.runAction(EditorUIAction.Type.OPEN_PROJECT, new FileModel(file.toURI()));
                }
            }
        });
        add(openItem);

        saveAllFile = createMenuItem("/save_all_btn.png");
        saveAllFile.setToolTipText("Save All");
        saveAllFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));
        saveAllFile.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                saveAllFile.setEnabled(false);
                MenuPane.this.actionManager.runAction(EditorUIAction.Type.SAVE);
            }
        });

        saveAllFile.setEnabled(false);
        add(saveAllFile);
    }

    public void enableSaveAllButton() {
        saveAllFile.setEnabled(true);
    }

    private JMenuItem createMenuItem(final String icon) {
        final JMenuItem jMenuItem = new JMenuItem();
        final Image image = new ImageIcon(TabbedEditorPane.class.getResource(icon)).getImage();
        final Icon imageIcon = new ImageIcon(image);
        jMenuItem.setIcon(imageIcon);
        return jMenuItem;
    }

}
